import 'package:flutter/material.dart';
import 'package:hm_pda_app/pages/incoming_goods.dart';
import 'package:hm_pda_app/pages/pending_reinspection.dart';
import 'package:hm_pda_app/pages/pending_delivery.dart';
import 'package:hm_pda_app/pages/stocking_and_warehousing.dart';
import 'package:hm_pda_app/pages/picking_goods.dart';
import 'package:hm_pda_app/pages/packing_goods.dart';
import 'package:hm_pda_app/pages/weighing_goods.dart';
import 'package:hm_pda_app/pages/outbound_inspection.dart';
import 'package:hm_pda_app/pages/pickup_goods.dart';
import 'package:hm_pda_app/pages/warehouse_relocation.dart';
import 'package:hm_pda_app/pages/inventory_check.dart';
import 'package:hm_pda_app/pages/inventory_inquiry.dart';
import 'package:hm_pda_app/pages/inventory_log.dart';
import 'package:hm_pda_app/pages/instock_defects.dart';
import 'package:hm_pda_app/pages/exchange.dart';
import 'package:hm_pda_app/pages/incoming_goods_inquiry.dart';
import 'package:hm_pda_app/components/top_header.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: null, body: const Center(child: HomeMenu()));
  }
}

// 菜单
class HomeMenu extends StatelessWidget {
  const HomeMenu({super.key});

  @override
  Widget build(BuildContext context) {
    return GridMenuScreen();
  }
}

class GridMenuScreen extends StatelessWidget {
  final List<Map<String, dynamic>> gridMenuItems = [
    {
      'title': '来货',
      'icon': Icons.local_shipping,
      'color': Colors.blue,
      'routerPage': IncomingGoodsPage(),
    },
    {
      'title': '复检',
      'icon': Icons.search,
      'color': Colors.green,
      'routerPage': PendingReinspectionScreen(),
    },
    {
      'title': '收货',
      'icon': Icons.inventory,
      'color': Colors.orange,
      'routerPage': PendingDelivery(),
    },
    {
      'title': '上架',
      'icon': Icons.shelves,
      'color': Colors.purple,
      'routerPage': StockingAndWarehousingPage(),
    },
    {
      'title': '拣货',
      'icon': Icons.shopping_basket,
      'color': Colors.red,
      'routerPage': PickingGoods(),
    },
    {
      'title': '打包贴标',
      'icon': Icons.inventory,
      'color': Colors.teal,
      'routerPage': PackingGoods(),
    },
    {
      'title': '装箱称重',
      'icon': Icons.scale,
      'color': Colors.pink,
      'routerPage': WeighingGoods(),
    },
    {
      'title': '出库校验',
      'icon': Icons.verified,
      'color': const Color.fromARGB(255, 101, 204, 70),
      'routerPage': OutboundInspection(),
    },
    {
      'title': '组包揽件',
      'icon': Icons.inventory_2,
      'color': const Color.fromARGB(255, 167, 79, 79),
      'routerPage': PickupGoods(),
    },
    {
      'title': '移库',
      'icon': Icons.move_up,
      'color': const Color.fromARGB(255, 161, 209, 48),
      'routerPage': WarehouseRelocation(),
    },
    {
      'title': '盘点',
      'icon': Icons.checklist,
      'color': const Color.fromARGB(255, 121, 9, 9),
      'routerPage': InventoryCheck(),
    },
    {
      'title': '库存查询',
      'icon': Icons.find_in_page,
      'color': const Color.fromARGB(255, 29, 129, 96),
      'routerPage': InventoryInquiry(),
    },
    {
      'title': '库存日志',
      'icon': Icons.history,
      'color': const Color.fromARGB(255, 150, 82, 82),
      'routerPage': InventoryLog(),
    },

    {
      'title': '库内不良',
      'icon': Icons.warning,
      'color': const Color.fromARGB(255, 209, 140, 140),
      'routerPage': InstockDefects(),
    },
    {
      'title': '换货',
      'icon': Icons.swap_horiz,
      'color': const Color.fromARGB(255, 231, 133, 41),
      'routerPage': Exchange(),
    },
    {
      'title': '来货查询',
      'icon': Icons.search,
      'color': const Color.fromARGB(255, 231, 133, 41),
      'routerPage': IncomingGoodsInquiry(),
    },
  ];

  GridMenuScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (bool didPop, dynamic result) async {
        if (didPop) return;

        // 在这里处理返回键操作
        print('返回键被按下');

        // 显示确认对话框
        bool shouldPop =
            await showDialog(
              context: context,
              builder: (context) => AlertDialog(
                title: Text('退出提示'),
                content: Text('确认返回桌面吗？'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: Text('取消'),
                  ),
                  TextButton(
                   onPressed: () async{
                   // Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => false)
                    final prefs = await SharedPreferences.getInstance();
                    final token =  prefs.getString('token');
                    print('返回监听---$token');
                    // Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => false);
                    SystemNavigator.pop();


                   },
                    child: Text('确定'),
                  ),
                ],
              ),
            ) ??
            false;

        if (shouldPop && context.mounted) {
          Navigator.of(context).pop();
        }
      },
      child: Scaffold(
        appBar: const TopHeader(title: '主页', showBackButton: false),
        endDrawer: const CustomDrawer(),
        resizeToAvoidBottomInset: false,
        // appBar: AppBar(
        //         backgroundColor: Colors.transparent,
        //         elevation: 0,
        //         toolbarHeight: 0,
        //       ),
        body: GridView.builder(
          padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3, // 每行3个
            // crossAxisSpacing: 2,
            // mainAxisSpacing: 2,
            childAspectRatio: 1.25, // 宽高比
          ),
          itemCount: gridMenuItems.length,
          itemBuilder: (context, index) {
            final item = gridMenuItems[index];
            return GridMenuItem(
              title: item['title'],
              icon: item['icon'],
              color: item['color'],
              onTap: () {
                _changePage(context, item['routerPage']);
              },
            );
          },
        ),
      ),
    );
  }
}

class GridMenuItem extends StatelessWidget {
  final String title;
  final IconData icon;
  final Color color;
  final VoidCallback onTap;

  const GridMenuItem({
    super.key,
    required this.title,
    required this.icon,
    required this.color,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(0)),

      elevation: 2,
      child: InkWell(
        onTap: onTap,
        // borderRadius: BorderRadius.circular(8),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // SizedBox(height: 20),
            Icon(icon, color: color, size: 24),
            Text(
              title,
              style: TextStyle(fontSize: 16),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
}

// 路由跳转
void _changePage(BuildContext context, Widget routerPage) {
  Navigator.push(
    context,
    MaterialPageRoute<void>(builder: (context) => routerPage),
  );
}
